import fetch from 'dva/fetch';
import router from 'umi/router';
function checkStatus(response) {
  if (response.status >= 200 && response.status < 300) {
    return response;
  }
  if (response.status === 401) {
    localStorage.clear();
    router.push('/login');
    const error = new Error('认证失败,请重新登陆');
    throw error;
  }

  const error = new Error(response.statusText);
  error.response = response;
  throw error;
}

// 统一状态处理
function checkCode(response) {
  if (response && response.code) {
    if(response.code === 401) {
      localStorage.clear();
      router.push('/login');
      const error = new Error('登陆超时，请重新登陆');
      throw error;
    }
    if (response.code !== 200 && response.code !== 201) {
      const error = new Error(response.msg);
      throw error;
    } else {
      return response;
    }
  }
}

/**
 * Requests a URL, returning a promise.
 *
 * @param  {string} url       The URL we want to request
 * @param  {object} [options] The options we want to pass to "fetch"
 * @return {object}           An object containing either "data" or "err"
 */
export default function request(url, options) {
  const defaultOptions = {
    // credentials: "include"
  };
  const newOptions = { ...defaultOptions, ...options };
  let tokenId = localStorage.getItem('tokenId') || '';
  if (tokenId && tokenId) {
    if (tokenId) {
      newOptions.headers = {
        accessToken: tokenId,
        ...newOptions.headers,
      };
    } else {
      newOptions.headers = {
        ...newOptions.headers,
      };
    }
  }
  if (newOptions.method === 'POST' || newOptions.method === 'PUT') {
    newOptions.headers = {
      Accept: 'application/json',
      'Content-Type': 'application/json; charset=utf-8',
      ...newOptions.headers,
    };
    newOptions.body = JSON.stringify(newOptions.body);
  }
  return fetch(url, newOptions)
    .then(checkStatus)
    .then(response => response.json())
    .then(checkCode);
  // .catch(err => err);
}
